package com.ssyc.student.activity;

import android.graphics.drawable.BitmapDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.makeramen.roundedimageview.RoundedImageView;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.ScreenUtils;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.ZzHorizontalProgressBar;
import com.ssyc.student.R;
import com.ssyc.student.bean.PersonInfo;
import com.ssyc.student.bean.ResultInfo;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;


public class StudentPersonInfoActivity extends BaseActivity implements View.OnClickListener {

    //标题栏
    private TextView tvTitle;

    //返回按钮
    private ImageView lvBack;
    private TextView tvStTitle;
    //个人中文名
    private TextView tvChineseName;
    //个人英文名
    private TextView tvEnglishName;
    //个人性别
    private TextView tvSex;
    //个人年龄
    private TextView tvAge;
    //个人生日
    private TextView tvBirthday;
    private LinearLayout llTop;
    private LinearLayout llBottom;


    //加载布局
    private RelativeLayout rlLoadingView;

    //内容布局
    private LinearLayout llContent;

    //经验值的进度条
    private ZzHorizontalProgressBar pbVigor;

    //个人头像
    private RoundedImageView lvPerson;

    //宠物姓名
    private TextView tvPetNickname;

    //宠物生日
    private TextView tvPetBirthday;

    //个性签名
    private TextView tvSignature;

    //宠物头像
    private RoundedImageView lvPet;

    //展示宠物等级的TextView
    private TextView tvLerver;

    //展示宠物经验值
    private TextView tvPbNum;

    //智
    private TextView tvZhi;
    //勇
    private TextView tvYong;
    //欢
    private TextView tvHuan;
    //爱
    private TextView tvAi;

    //宠物性别
    private TextView tv_pet_sex;

    //编辑签名的View
    private View view;

    //弹窗
    private PopupWindow popupWindow;

    private RelativeLayout rlPopClose;
    private RelativeLayout rlPopOut;
    private EditText etInput;
    private TextView tvNum;
    //签名保存按钮
    private Button btSave;

    private String acc;

    private String userid;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_person_info;
    }

    @Override
    protected void init() {
        showContent();

        //初始化视图
        initView();
        //接受数据
        initIntent();
        //请求服务器获取页面数据
        http();
    }

    /**
     * 接受数据
     */
    private void initIntent() {
        userid = getIntent().getStringExtra("userid");

        if (TextUtils.isEmpty(userid)) {
            acc = AccountUtils.getAccount(this);
        } else {
            acc = userid;
        }

        if (!TextUtils.isEmpty(userid)) {
            //签名不可编辑
            tvSignature.setClickable(false);
            tvSignature.setText("暂无签名");
            tvTitle.setText("好友资料");
        }
    }


    /**
     * 请求服务器获取页面数据
     */
    private void http() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "6");
        map.put("platform", "8");
        map.put("acc", acc);
        map.put("role", AccountUtils.getRole(this));
//      map.put("apptoken", AccountUtils.getToken(this));
        Log.i("test", "role=" + AccountUtils.getRole(this) + "&acc=" + AccountUtils.getAccount(this) + "&apptoken=" + AccountUtils.getToken(this));

        HttpUtils.post(HttpAdress.PERSONINFO, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoadingView) {
                    rlLoadingView.setVisibility(View.GONE);
                }

                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {

                if (null != rlLoadingView) {
                    rlLoadingView.setVisibility(View.GONE);
                }

                if (null != llContent) {
                    llContent.setVisibility(View.VISIBLE);
                }

                //解析返回服务器返回的JSON数据
                PersonInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, PersonInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "解析服务器返回数据异常");
                }
                Log.i("test", "个人资料：" + response);

                if (info != null) {
                    //请求成功
                    if ("200".equals(info.getState())) {
                        if (info.getData() != null && info.getData().size() != 0) {

                            //保存姓名
                            SPUtil.put(StudentPersonInfoActivity.this, SpKeys.NAME, info.getData().get(0).getStudent_name());

                            //保存头像
                            SPUtil.put(StudentPersonInfoActivity.this, SpKeys.ICON, info.getData().get(0).getStudent_icon());

                            //学生头像
                            ImageUtil.displayImage(getBaseContext(), lvPerson
                                    , info.getData().get(0).getStudent_icon(), R.drawable.student_def_headimg);

                            //学生姓名
                            tvChineseName.setText(info.getData().get(0).getStudent_name());

                            //学生英文名
                            tvEnglishName.setText(info.getData().get(0).getStudent_english_name());

                            //学生性别
                            if ("1".equals(info.getData().get(0).getStudent_sex())) {
                                tvSex.setText("男");
                            } else if ("2".equals(info.getData().get(0).getStudent_sex())) {
                                tvSex.setText("女");
                            }
                            //学生年龄
                            tvAge.setText(info.getData().get(0).getStudent_age());

                            //学生生日
                            tvBirthday.setText(info.getData().get(0).getStudent_birthday());

                            //个性签名
                            if (info.getData().get(0).student_user_sign != null &&
                                    !"".equals(info.getData().get(0).student_user_sign)) {
                                tvSignature.setText(info.getData().get(0).student_user_sign);
                            }

                            //宠物姓名
                            tvPetNickname.setText(info.getData().get(0).getNick_name());

                            //宠物性别
                            if ("1".equals(info.getData().get(0).getGender())) {
                                tv_pet_sex.setText("男");
                            } else if ("0".equals(info.getData().get(0).getGender())) {
                                tv_pet_sex.setText("女");
                            }
                            //宠物生日
                            tvPetBirthday.setText(info.getData().get(0).getPet_birthday());

                            //宠物头像
                            if ("1".equals(info.getData().get(0).getPet_id())) {
                                lvPet.setImageResource(R.drawable.base_pet_icon1);
                            } else if ("2".equals(info.getData().get(0).getPet_id())) {
                                lvPet.setImageResource(R.drawable.base_pet_icon2);
                            } else if ("3".equals(info.getData().get(0).getPet_id())) {
                                lvPet.setImageResource(R.drawable.base_pet_icon3);
                            } else if ("4".equals(info.getData().get(0).getPet_id())) {
                                lvPet.setImageResource(R.drawable.base_pet_icon4);
                            }

//                          ImageUtil.displayImage(getBaseContext(), lvPet
//                                    , info.getData().get(0).getPet_icon(), R.drawable.defaultimage);


                            int curr = Integer.parseInt(info.getData().get(0).exp);

                            int max = 0;

                            if (!TextUtils.isEmpty(info.getData().get(0).getExp_next())) {
                                max = Integer.parseInt(info.getData().get(0).getExp_next());
                            }

                            if (max == 0) {

                                //宠物满级了,进度条也是100
                                pbVigor.setProgress(100);

                            } else {

                                if (curr > max) {
                                    //经验值条
                                    pbVigor.setProgress(100);
                                } else {
                                    //经验值条
                                    pbVigor.setProgress((int) ((float) curr / (float) max * 100));
                                }
                            }


                            //经验值
                            if (TextUtils.isEmpty(info.getData().get(0).getExp_next())) {
                                tvPbNum.setText(info.getData().get(0).exp + "/0");

                            } else {
                                tvPbNum.setText(info.getData().get(0).exp + "/" + info.getData().get(0).getExp_next());
                            }

                            //宠物等级
                            tvLerver.setText("LV." + info.getData().get(0).getLevel());


                            //智勇欢爱
                            tvZhi.setText(info.getData().get(0).getWisdom());
                            tvYong.setText(info.getData().get(0).getBrave());
                            tvHuan.setText(info.getData().get(0).getJoy());
                            tvAi.setText(info.getData().get(0).getLove());

                        }
                    }
                }
            }
        });
    }


    /**
     * 初始化View的操作
     */
    public void initView() {
        tvTitle = findViewById(R.id.tv_st_title);
        lvBack = findViewById(R.id.iv_back);
        lvBack.setOnClickListener(this);
        tvStTitle = findViewById(R.id.tv_st_title);
        tvChineseName = findViewById(R.id.tv_chinese_name);
        tvEnglishName = findViewById(R.id.tv_english_name);
        tvSex = findViewById(R.id.tv_sex);
        tvAge = findViewById(R.id.tv_age);
        tvBirthday = findViewById(R.id.tv_birthday);
        llTop = findViewById(R.id.ll_top);

        tvPetNickname = findView(R.id.tv_pet_nickname);
        tvPetBirthday = findView(R.id.tv_pet_birthday);
        tv_pet_sex = findView(R.id.tv_pet_sex);

        tvPbNum = findView(R.id.tv_pb_num);

        tvZhi = findView(R.id.tv_zhi);

        tvYong = findView(R.id.tv_yong);

        tvHuan = findView(R.id.tv_huan);

        tvAi = findView(R.id.tv_ai);

        //动画计算整体布局的大小
        int width = ScreenUtils.getScreenWidth(this) - 12 * 2;

        llBottom = findViewById(R.id.ll_tottom);

        pbVigor = findViewById(R.id.pb_vigor);
        pbVigor.setBgColor(getResources().getColor(R.color.pb_bg));
        pbVigor.setProgressColor(getResources().getColor(R.color.pb_progress_color));

        //动态计算个人图片和宠物图片的宽高
        lvPerson = findViewById(R.id.lv_person);
        lvPet = findViewById(R.id.lv_pet);

        //设置个人头像的大小
        RelativeLayout.LayoutParams lpPerson = new RelativeLayout.LayoutParams(width * 118 / 350, width * 108 / 350);
        lvPerson.setLayoutParams(lpPerson);

        //设置宠物头像的的大小
        RelativeLayout.LayoutParams lpPet = new RelativeLayout.LayoutParams(width * 110 / 350, width * 104 / 350);
        lpPet.topMargin = width * 2 / 350;
        lpPet.leftMargin = width * 2 / 350;
        lvPet.setLayoutParams(lpPet);

        //设置个性签名的大小
        tvSignature = findViewById(R.id.tv_signature);
        tvSignature.setOnClickListener(this);
        //展示宠物等级的文字
        tvLerver = findViewById(R.id.tv_lerver);


        //做45度的旋转动画
        RotateAnimation rotate = new RotateAnimation(0f, -45f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        LinearInterpolator lin = new LinearInterpolator();
        rotate.setInterpolator(lin);
        rotate.setDuration(10);
        rotate.setFillAfter(true);
        tvLerver.setAnimation(rotate);

        rlLoadingView = findViewById(R.id.rl_loading);
        llContent = findViewById(R.id.ll_content);
        rlLoadingView.setVisibility(View.VISIBLE);
        llContent.setVisibility(View.GONE);

    }


    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.tv_signature) {
            //编辑签名
            showSignPop();
        }
    }


    /**
     * 先判断是否输入了签名,然后上传服务器,最后关闭PopUpWindow
     */
    private void doPostSignAction() {
        if (TextUtils.isEmpty(etInput.getText().toString().trim())) {
            UIHelper.showToast(this, "输入签名不能为空");
            return;
        }

        //上传服务器
        upload(etInput.getText().toString().trim());

        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    /**
     * 上传个性签名
     */
    private void upload(String content) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "34");
        map.put("c", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("sign", content);
        map.put("platform", "8");
        HttpUtils.post(HttpAdress.SIGN, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    //解析返回服务器返回的JSON数据
                    ResultInfo info = GsonUtil.jsonToBean(response, ResultInfo.class);

                    Log.i("test", response);

                    //请求成功
                    if ("200".equals(info.state)) {
                        tvSignature.setText(content);
                        UiUtils.Toast("签名编辑成功", false);
                    } else {
                        UiUtils.Toast("编辑失败，请稍后重试", false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "解析服务器返回数据异常");
                }
            }
        });
    }


    /**
     * 弹框编辑个性签名的方法
     */
    private void showSignPop() {


        view = View.inflate(this, R.layout.student_pop_sign, null);
        rlPopClose = view.findViewById(R.id.rl_close);
        rlPopOut = view.findViewById(R.id.rl_pop_out);
        etInput = view.findViewById(R.id.et_input);
        tvNum = view.findViewById(R.id.tv_num);
        btSave = view.findViewById(R.id.bt_save);
        rlPopClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
        btSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //保存
                doPostSignAction();
            }
        });
        rlPopOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
        //设置输入监听
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String content = etInput.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    tvNum.setText("0/50");
                } else {
                    if (content.length() > 50) {
                        UIHelper.showToast(StudentPersonInfoActivity.this, "最多只能输入50字");
                        return;
                    } else {
                        tvNum.setText(content.length() + "/50");
                    }
                }
            }
        });

        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //配置动画
        popupWindow.setAnimationStyle(R.style.st_pop_second_menu);
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }
}
